const express = require('express');
const router = express.Router();
const { getKnex } = require('../db/knex');
const Result = require('../utils/Result');

// 查询分类列表
router.get('/', async (req, res) => {
  try {
    const knex = getKnex();
    const categories = await knex('categories').select('*').orderBy('id');
    res.json(Result.success(categories));
  } catch (error) {
    console.error(error);
    res.json(Result.fail('查询分类失败'));
  }
});

// 新增分类
router.post('/', async (req, res) => {
  try {
    const knex = getKnex();
    const { name } = req.body;

    const [id] = await knex('categories').insert({ name });
    res.json(Result.success({ id }, '分类添加成功'));
  } catch (error) {
    console.error(error);
    res.json(Result.fail('分类添加失败'));
  }
});

// 更新分类
router.put('/:id', async (req, res) => {
  try {
    const knex = getKnex();
    const id = req.params.id;
    const { name, description } = req.body;

    await knex('categories').where({ id }).update({ name, description });
    res.json(Result.success(null, '分类更新成功'));
  } catch (error) {
    console.error(error);
    res.json(Result.fail('分类更新失败'));
  }
});

// 删除分类
router.delete('/:id', async (req, res) => {
  try {
    const knex = getKnex();
    const id = req.params.id;
    await knex('categories').where({ id }).del();
    res.json(Result.success(null, '分类删除成功'));
  } catch (error) {
    console.error(error);
    res.json(Result.fail('分类删除失败'));
  }
});

module.exports = router;
